package com.chb.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
 * @author CHB
 * @createTime 2022-8-24 9:58
 */
public class BeanUtils {
    /**
     * 拷贝列表对象并返回，本质上是对BeanUtils.copyProperties()的简单封装
     * handler用以支持自定义拷贝规则
     *
     * @param sources 源列表对象
     * @param targetSupplier 目标对象
     * @param handler 自定义处理器
     * @return List<T>
     * @author CHB
     * @date 2022-06-10 11:18
     */
    public static <S, T> List<T> copyBeanList(List<S> sources, Supplier<T> targetSupplier, BiConsumer<S, T> handler){
        if(sources == null || targetSupplier == null){
            return Collections.emptyList();
        }
        List<T> copyList = new ArrayList<>(sources.size());
        for (S source : sources) {
            copyList.add(copyBean(source, targetSupplier, handler));
        }
        return copyList;
    }
    /**
     * 拷贝列表对象方法重载
     *
     * @param sources 源列表对象
     * @param targetSupplier 目标对象
     * @return List<T>
     * @author CHB
     * @date 2022-06-10 11:28
     */
    public static <S, T> List<T> copyBeanList(List<S> sources, Supplier<T> targetSupplier){
        return copyBeanList(sources,targetSupplier,null);
    }

    /**
     * 拷贝对象并返回，本质上是对BeanUtils.copyProperties()的简单封装
     * handler用以支持自定义拷贝规则
     *
     * @param source 源对象
     * @param targetSupplier 目标对象
     * @param handler 自定义处理器
     * @return T
     * @author CHB
     * @date 2022-06-10 11:18
     */
    public static <S, T> T copyBean(S source, Supplier<T> targetSupplier, BiConsumer<S, T> handler){
        if(source == null || targetSupplier == null){
            return null;
        }
        T target = targetSupplier.get();
        org.springframework.beans.BeanUtils.copyProperties(source,target);
        if(handler != null){
            handler.accept(source,target);
        }
        return target;
    }

    /**
     * 拷贝对象方法重载
     *
     * @param source 源对象
     * @param targetSupplier 目标对象
     * @return T
     * @author CHB
     * @date 2022-06-10 11:18
     */
    public static <S, T> T copyBean(S source, Supplier<T> targetSupplier){
        return copyBean(source,targetSupplier,null);
    }
}
